# This file contains a number of image manipulation functions.

import StringIO
import Image, ImageEnhance, ImageFilter, ImageOps
import gtk

class Conversion:
    # This function was snatched from some web page.
    # Thanks to Sebastian Wilhelmi who wrote it :-)
    @classmethod
    def image2pixbuf(cls, image):
        file = StringIO.StringIO()
        image.save(file, 'ppm')
        contents = file.getvalue()
        file.close()
        loader = gtk.gdk.PixbufLoader('pnm')
        loader.write(contents, len(contents))
        pixbuf = loader.get_pixbuf()
        loader.close()
        return pixbuf

    # Also snatched from the web. Thanks to Christian Robottom Reis... I think?
    @classmethod
    def pixbuf2image(cls, pixbuf):
        return Image.fromstring("RGB",(pixbuf.get_width(),pixbuf.get_height()), pixbuf.get_pixels())

class ImageHandling:
    @classmethod
    def adjust_size_to_maintain_aspect(cls, original_size, desired_size):
        scale = float(desired_size[0])/original_size[0]
        if original_size[1] * scale <= desired_size[1]:
            height = int(original_size[1] * scale)
            if height > desired_size[1]:
                height = desired_size[1]
            return (desired_size[0], height)
        else:
            scale = float(desired_size[1])/original_size[1]
            width = int(original_size[0] * scale)
            if width > desired_size[0]:
                width = desired_size[0]
            return (width, desired_size[1])
        

    @classmethod
    def simple_scale(cls, image, width, height):
        """
        Scales an image for display on a monitor with the given resolution. 
        This function maintains the aspect ratio of the image.
        @type image: Image
        @param image: The image that is to be scaled.
        @type width: int
        @param width: The target width.
        @type height: int
        @param height: The target height. 
        """
        # Find out which side to scale on.
        size = ImageHandling.adjust_size_to_maintain_aspect(image.size, (width, height))
        return image.resize(size, Image.NEAREST)


    
        